Telegram Group & Telegram Channel
В Python объекты хранят свои атрибуты в словарях, доступ к которым можно получить через магический атрибут dict:


class A: pass
a = A()
a.x = 1
a.__dict__
# {'x': 1}


При прямом доступе к этому словарю можно даже создать атрибуты, которые не являются допустимыми идентификаторами Python (то есть получить их через стандартный синтаксис obj.attr не получится):


a.__dict__[' '] = ' '
getattr(a, ' ')
# ' '


Можно также попросить Python хранить атрибуты непосредственно в памяти (как у простых структур C) с помощью slots. Это экономит память и немного ускоряет доступ к атрибутам, так как не происходит поиска в словаре.


class Point:
__slots__ = ['x', 'y']


Есть несколько моментов, которые нужно помнить при использовании slots. Во-первых, нельзя задавать атрибуты, не указанные в slots. Во-вторых, если класс наследуется от класса с slots, его slots не перекрывают родительские, а добавляются к ним:


class Parent: __slots__ = ['x']
class Child(Parent): __slots__ = ['y']
c = Child()
c.x = 1
c.y = 2


В-третьих, нельзя наследоваться сразу от двух разных классов с непустыми slots, даже если они совпадают.

Помни, что slots предназначены для оптимизации, а не для ограничения набора атрибутов.

👉@BookPython



tg-me.com/BookPython/3678
Create:
Last Update:

В Python объекты хранят свои атрибуты в словарях, доступ к которым можно получить через магический атрибут dict:


class A: pass
a = A()
a.x = 1
a.__dict__
# {'x': 1}


При прямом доступе к этому словарю можно даже создать атрибуты, которые не являются допустимыми идентификаторами Python (то есть получить их через стандартный синтаксис obj.attr не получится):


a.__dict__[' '] = ' '
getattr(a, ' ')
# ' '


Можно также попросить Python хранить атрибуты непосредственно в памяти (как у простых структур C) с помощью slots. Это экономит память и немного ускоряет доступ к атрибутам, так как не происходит поиска в словаре.


class Point:
__slots__ = ['x', 'y']


Есть несколько моментов, которые нужно помнить при использовании slots. Во-первых, нельзя задавать атрибуты, не указанные в slots. Во-вторых, если класс наследуется от класса с slots, его slots не перекрывают родительские, а добавляются к ним:


class Parent: __slots__ = ['x']
class Child(Parent): __slots__ = ['y']
c = Child()
c.x = 1
c.y = 2


В-третьих, нельзя наследоваться сразу от двух разных классов с непустыми slots, даже если они совпадают.

Помни, что slots предназначены для оптимизации, а не для ограничения набора атрибутов.

👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3678

View MORE
Open in Telegram


Библиотека Python разработчика | Книги по питону Telegram | DID YOU KNOW?

Date: |

Should You Buy Bitcoin?

In general, many financial experts support their clients’ desire to buy cryptocurrency, but they don’t recommend it unless clients express interest. “The biggest concern for us is if someone wants to invest in crypto and the investment they choose doesn’t do well, and then all of a sudden they can’t send their kids to college,” says Ian Harvey, a certified financial planner (CFP) in New York City. “Then it wasn’t worth the risk.” The speculative nature of cryptocurrency leads some planners to recommend it for clients’ “side” investments. “Some call it a Vegas account,” says Scott Hammel, a CFP in Dallas. “Let’s keep this away from our real long-term perspective, make sure it doesn’t become too large a portion of your portfolio.” In a very real sense, Bitcoin is like a single stock, and advisors wouldn’t recommend putting a sizable part of your portfolio into any one company. At most, planners suggest putting no more than 1% to 10% into Bitcoin if you’re passionate about it. “If it was one stock, you would never allocate any significant portion of your portfolio to it,” Hammel says.

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

Библиотека Python разработчика | Книги по питону from de


Telegram Библиотека Python разработчика | Книги по питону
FROM USA